/*
request:
baby/new?relation=1&sid=xxx&uid=xxx
POST:
{"name":"wangwanchen","nick":"chenchen","birthday":"2013-05-10 10:49:00","gender":1,"header":"http://xxxx"}
*/

package controllers

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"

	"conf"
	"models"
	"models/response"
)

type BabyCraeteController struct {
	beego.Controller
}

func (this *BabyCraeteController) Post() {

	var result response.Response

	relation := this.Input().Get("relation")
	fmt.Println("relation:", relation)

	uid := this.GetString("uid")
	if uid == "" {
		result.Message = response.Info_Error_ParamError
		result.Ret = response.Code_Error_ParamError
		this.Ctx.WriteString(result.FormatJsonString())
	}

	var postJson string
	postJson = fmt.Sprintf("%s", this.Ctx.RequestBody)
	fmt.Println(postJson)

	var baby models.Baby

	json.Unmarshal([]byte(postJson), &baby)
	baby.Id = bson.NewObjectId()
	baby.CreateTime = time.Now()
	baby.CreateUserId = uid

	if relationIntValue, err := strconv.Atoi(fmt.Sprintf("%v", relation)); err == nil {
		j1 := make(map[string]int)
		j1[uid] = relationIntValue
		baby.Relations = j1
	}

	fmt.Println("baby is %v:", baby)
	//return
	session, err := mgo.Dial(config.DataBaseIP)
	if err != nil {
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}

	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	fmt.Println("insert baby info")
	c := session.DB(config.DataBaseName).C(config.DataTableBaby)
	err = c.Insert(&baby)
	if err != nil {
		fmt.Printf("error:%s\n", err)
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}

	fmt.Println("quer after insert")
	resultBaby := models.Baby{}
	err = c.Find(bson.M{"_id": baby.Id}).One(&resultBaby)
	if err != nil {
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}

	fmt.Println("quer finish:", resultBaby)

	result.Message = response.Info_Success
	result.Ret = response.Code_Success
	result.Data = resultBaby

	this.Ctx.WriteString(result.FormatJsonString())
}

func (this *BabyCraeteController) Get() {
	this.Ctx.WriteString("baby new get\n")
}
